﻿using System;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Windows.Forms;

namespace NExplorer.AddIns.Samples.Forms
{
    public sealed partial class PasteClipboardToFileForm : Form
    {
        public PasteClipboardToFileForm()
        {
            InitializeComponent();

            Font = SystemFonts.DialogFont;
        }

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            if (Clipboard.ContainsAudio())
            {
                dataTypeCombo.Items.Add("Audio");
            }

            if (Clipboard.ContainsImage())
            {
                dataTypeCombo.Items.Add("Image");
            }

            if (Clipboard.ContainsText())
            {
                dataTypeCombo.Items.Add("Text");
            }

            dataTypeCombo.SelectedIndex = 0;
        }

		protected override void OnActivated(EventArgs e)
		{
			base.OnActivated(e);

			filenameTextBox.Focus();
		}

        private string Filename
        {
            get
            {
				// The menu builder only shows this feature when a single directory is selected, so
				// we can continue assuming that is correct.
                return Path.Combine(ServiceManager.Explorer.SelectedItems[0].FullName, filenameTextBox.Text.Trim());
            }
        }

        private void okButton_Click(object sender, EventArgs e)
        {
            switch ((string)dataTypeCombo.SelectedItem)
            {
                case "Image":
                    Image image = Clipboard.GetImage();
                    image.Save(Filename);
                    break;

                case "Text":
                    File.WriteAllText(Filename, Clipboard.GetText());
                    break;

                case "Audio":
                    using (FileStream writer = new FileStream(Filename, FileMode.CreateNew))
                    {
                        Stream stream = Clipboard.GetAudioStream();
                        byte[] buffer = new byte[65536];
                        int read;

                        do
                        {
                            read = stream.Read(buffer, 0, buffer.Length);
                            writer.Write(buffer, 0, read);
                        } while (read != 0);

                        writer.Close();
                    }

                    break;
            }

            if (openFileAfterSavingCheckBox.Checked)
            {
                Process.Start(Filename);
            }
        }

        private void filenameTextBox_TextChanged(object sender, EventArgs e)
        {
            okButton.Enabled = !File.Exists(Filename) && filenameTextBox.Text.IndexOfAny(Path.GetInvalidFileNameChars()) == -1;
        }
    }
}
